﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using QDT.Common;
using QDT.Core.Deals;
using QDT.Core.Members;
using QDT.Core.Projects;

namespace QDT.Web.Controllers
{
    public class DataController : BaseController
    {
        private const string UserName = "qiandt";
        private const string Password = "qiandt";

        public ActionResult Login(string userName, string password)
        {
            var result = 0;
            var token = "";
            if (userName.Equals(UserName) && password.Equals(Password))
            {
                result = 1;
                token = Token();
            }
            var data = new{ token };

            return Json(new { @return = result, data }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetNowProjects(string token)
        {
            if (!token.ToLower().Equals(Token()))
            {
                return Json(new { @return = 0, data = "请先登陆" }, JsonRequestBehavior.AllowGet);
            }
            var projects = DbProvider.D<Project>().Where(x => x.InnerStatus.Equals((int)ProjectStatus.Progress) && !x.IsOffline && x.IsEffect && !x.IsDelete).ToList();

            var data = GetProjects(projects);

            return Json(new { @return = 1, data }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetProjectsByDate(string token, DateTime date)
        {
            if (!token.ToLower().Equals(Token()))
            {
                return Json(new { @return = 0, data = "请先登陆" }, JsonRequestBehavior.AllowGet);
            }
            var start = date.Date;
            var end = start.AddDays(1);
            var projects =
                DbProvider.D<Project>()
                    .Where(
                        x =>
                            x.RepayStartTime >= start && x.RepayStartTime < end && !x.InnerStatus.Equals((int)ProjectStatus.Bad) &&
                            !x.IsOffline && x.IsEffect && !x.IsDelete)
                    .ToList();

            var data = GetProjects(projects);

            return Json(new { @return = 1 ,data }, JsonRequestBehavior.AllowGet);
        }

        private object GetProjects(IEnumerable<Project> projects)
        {
            var data = projects.Select(x => new
            {
                projectId = x.ID,
                title = x.Name,
                amount = x.BorrowAmount,
                schedule = x.Progress,
                interestRate = x.Rate + "%",
                deadline = x.RepayTime,
                deadLineUnit = "月",
                reward = "0",
                type = GetTypeName(x.TypeID),
                repaymentType = "5",
                loanUrl = GetProjectUri(x.ID),
                publishTime = x.StartTime.HasValue ? x.StartTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                successTime = x.RepayStartTime.HasValue ? x.RepayStartTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                userName = GetUserName(x.UserID),
                subscribes = GetCredits(x.ID),
                totalShares = "0",
                castedShares = "0",
                province = "",
                city = "",
                userAvatarUrl = "",
                amountUsedDesc = "",
                revenue = "",
            });
            return data;
        }

        private object GetCredits(int pid)
        {
            var credits = DbProvider.D<Credit>().Where(x => x.ProjectID.Equals(pid)).ToList();
            var data = credits.Select(x => new
            {
                status = "1",
                amount = x.BuyMoney,
                validAmount = x.Money,
                type = x.IsAuto,
                addDate = x.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                subscribeUserName = x.UserName
            });
            return data;
        }

        private static string Token()
        {
            return (UserName + Password + DateTime.Now.Date).Hash().ToLower();
        }

        private string GetTypeName(int id)
        {
            var result = DbProvider.D<ProjectType>().FirstOrDefault(x => x.ID == id);
            return result != null ? result.Name : "未分配";
        }

        private string GetUserName(int id)
        {
            var result = DbProvider.D<User>().FirstOrDefault(x => x.ID == id);
            return result != null ? result.UserName : "未分配";
        }

        private static string GetProjectUri(int id)
        {
            return @"http://www.zxidai.com/Project/Index/{0}".FormatWith(id);
        }

    }


}
